package inf.subscribersManagement;

import inf.exceptions.*;
import inf.hibernateUtils.HibernateUtil;
import inf.mediasManagement.Media;
import inf.subscribersManagement.Subscriber;

import java.util.List;


import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;


public class SubscriberDAO {

	/** 
	 * Tests the presence of any subscriber in DB
	 * 
	 * @return
	 */
 	public boolean isEmpty(){
		Session session = HibernateUtil.openSession();
		Query query = session.createQuery("from subscribers");
		List<Media> medias = query.list();
		if (medias.isEmpty())
			return true;
		else
			return false;	
	}

 	public static boolean save(Subscriber subscriber){
 		return SubscriberDAO.add(subscriber);
 	}
 	
	/**
	 * Adds a subscriber in the persistence unit (hence in DB)
	 * 
	 * @param subscriber
	 * @return
	 */
	public static boolean add(Subscriber subscriber){
		Session session= HibernateUtil.openSession();
		try{
			session.saveOrUpdate(subscriber);
		} catch (Exception e) {
			System.err.println("Problem when saving");
			e.printStackTrace();
			return false;
		}
	
		return true;
	}

	/**
	 * Removes a subscriber in the persistence unit (hence in DB)
	 * 
	 * @param subscriber
	 * @return
	 */
	public static boolean remove(Subscriber subscriber){
		Session session = HibernateUtil.openSession();
		try{
			session.delete(subscriber);
		} catch (Exception e) {
			System.err.println("Problem when saving");
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static boolean contains(Subscriber subscriber) throws MediaExistsException {
		Session session = HibernateUtil.openSession();
		if (subscriber== null) throw new MediaExistsException();
		Subscriber s = (Subscriber) session.get(Subscriber.class, subscriber.getId());
		if (s ==null) return false;
		else return s.equals(subscriber);	
	}
	
	
	public static Subscriber GetSingleSubscriberByLastName(String lastName) throws SubscriberExistsException {
		Session session = HibernateUtil.openSession();
		Criteria criteria = session.createCriteria(Subscriber.class).add(Restrictions.eq("lastName", lastName));
		Subscriber subscriber = (Subscriber)criteria.uniqueResult();
		if (subscriber == null) throw new SubscriberExistsException();
		else
			return subscriber;
	}
	
	public static Subscriber get(long id) throws SubscriberExistsException {
		Session session = HibernateUtil.openSession();
		Criteria criteria = session.createCriteria(Subscriber.class).add(Restrictions.eq("id", id));
		Subscriber subscriber = (Subscriber) criteria.uniqueResult();
		if (subscriber == null) throw new SubscriberExistsException();
		else
			return subscriber;
	}	
}
